<template>
  <el-container style="background-color: #f3f3f4;">
    <el-aside
      style="margin-left:10px;   height: 100%; border: 1px solid #eee; width:25%;background-color: #fff;"
    >
      <!--左侧搜索条件-->
      <div class="material-filter-container">
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-input v-model="listQuery.keyword" placeholder="关键字" style="width:90%;" clearable/>
          </el-col>

          <el-col :span="4" :offset="0">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="searchFrom"
            >{{ $t('table.search') }}</el-button>
          </el-col>

          <el-col :span="4" :offset="1">
            <!--弹出添加框start-->
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-edit"
              disabled="true"
              @click="dialogFormVisible = true"
            >{{ $t('table.add') }}</el-button>
            <el-dialog
              :visible.sync="dialogFormVisible"
              :before-close="dialogCancle"
              title="添加发货记录"
              width="60%"
            >
              <el-form
                ref="dynamicValidateForm"
                :rules="rules"
                :inline="true"
                :model="dynamicValidateForm"
                label-width="80px"
                class="demo-form-inline"
              >
                <el-form-item label="收款公司" prop="proceedCompany">
                  <el-select
                    v-model="dynamicValidateForm.proceedCompany"
                    placeholder="请选择收款公司"
                    style="width: 250px;"
                    filterable
                  >
                    <el-option
                      v-for="proceedCompany in proceedCompanyList"
                      :label="proceedCompany.text"
                      :value="proceedCompany.value"
                      :key="proceedCompany.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="合作商" prop="supplierName">
                  <el-select
                    v-model="dynamicValidateForm.supplierName"
                    placeholder="请选择合作商"
                    style="width: 250px;"
                    filterable
                  >
                    <el-option
                      v-for="supplierName in partnerList"
                      :label="supplierName.text"
                      :value="supplierName.value"
                      :key="supplierName.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="供货商" prop="partnerId">
                  <el-select
                    v-model="dynamicValidateForm.partnerId"
                    placeholder="请选择供货商"
                    style="width: 250px;"
                    filterable
                  >
                    <el-option
                      v-for="supplierName in supplierNameList"
                      :label="supplierName.text"
                      :value="supplierName.value"
                      :key="supplierName.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="分销商" prop="disId">
                  <el-select
                    v-model="dynamicValidateForm.disId"
                    placeholder="请选择分销商"
                    style="width: 250px;"
                    filterable
                  >
                    <el-option
                      v-for="dis in disList"
                      :label="dis.disName"
                      :value="dis.disId"
                      :key="dis.disId"
                    />
                  </el-select>
                </el-form-item>
                <!-- <el-form-item label="总金额" prop="productTotalAmount">
                            <el-input  placeholder="0.00" v-model="dynamicValidateForm.productTotalAmount" style="width: 250px;" clearable/>
                </el-form-item>-->
                <el-form-item label="发货日期" prop="shipmentCreateDatetime">
                  <el-date-picker
                    v-model="dynamicValidateForm.shipmentCreateDatetime"
                    type="date"
                    placeholder="选择日期"
                    style="width:250px;"
                  />
                </el-form-item>
                <el-form-item label="发货单号" prop="shipmentNo">
                  <el-input
                    v-model="dynamicValidateForm.shipmentNo"
                    style="width: 250px;"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="添加明细">
                  <el-button style="margin-left:80px;" @click="addDetail">+</el-button>
                </el-form-item>

                <el-form-item
                  v-for="(detail, index) in dynamicValidateForm.details"
                  :label="'物资明细'"
                  :key="index"
                >
                  <el-form-item
                    :prop="'details.' + index + '.productName'"
                    :rules="[{required: true, message: '名称不能为空', trigger: 'blur' }]"
                    label="产品名称"
                    style="margin-top:20px;"
                  >
                    <el-input v-model="detail.productName" clearable style="width: 200px"/>
                  </el-form-item>
                  <el-form-item label="产品规格" style="margin-top:20px;">
                    <el-input
                      v-model="detail.productSpecifications"
                      clearable
                      style="width:200px;"
                    />
                  </el-form-item>

                  <el-form-item
                    :prop="'details.' + index + '.productCnt'"
                    :rules="[
                      {required: true, message: '数量不能为空', trigger: 'blur'},
                      { type: 'number', message: '数量必须为数字值', trigger: 'blur'}]"
                    label="数量"
                    style="margin-top:20px;"
                  >
                    <el-input
                      v-model.number="detail.productCnt"
                      style="width: 200px;"
                      clearable
                      autocomplete="off"
                    />
                  </el-form-item>

                  <el-form-item
                    :prop="'details.' + index + '.productUpPrice'"
                    :rules="[
                      {required: true, message: '单价不能为空', trigger: 'blur'},
                      {type: 'number', message: '单价必须为数字值', trigger: 'blur'}
                    ]"
                    label="上游单价"
                    style="margin-top:20px;"
                  >
                    <el-input
                      v-model.number="detail.productUpPrice"
                      clearable
                      style="width: 200px;"
                    />
                  </el-form-item>

                  <el-form-item
                    :prop="'details.' + index + '.productDownPrice'"
                    :rules="[
                      {required: true, message: '单价不能为空', trigger: 'blur'},
                      {type: 'number', message: '单价必须为数字值', trigger: 'blur'}
                    ]"
                    label="下游单价"
                    style="margin-top:20px;"
                  >
                    <el-input
                      v-model.number="detail.productDownPrice"
                      clearable
                      style="width: 200px;"
                    />
                  </el-form-item>

                  <el-form-item label="单位" style="margin-top:20px;">
                    <el-input v-model="detail.productUnit" clearable style="width: 200px;"/>
                  </el-form-item>
                  <el-form-item label="品类" style="margin-top:20px;">
                    <el-input v-model="detail.productCategory" clearable style="width:200px;"/>
                  </el-form-item>
                  <el-form-item label="品牌" style="margin-top:20px;">
                    <el-input v-model="detail.productBrand" clearable style="width:200px;"/>
                  </el-form-item>
                  <el-form-item label="联系电话" style="margin-top:20px;">
                    <el-input v-model="detail.customerPhone" clearable style="width:200px;"/>
                  </el-form-item>
                  <el-form-item label="联系人" style="margin-top:20px;">
                    <el-input v-model="detail.customerName" clearable style="width:200px;"/>
                  </el-form-item>

                  <el-button
                    style="margin-top:20px;margin-left:20px;"
                    @click.prevent="resetForm(detail)"
                  >重置</el-button>
                  <el-button
                    type="danger"
                    style="margin-top:20px;margin-left:20px;"
                    @click.prevent="removeDetail(detail)"
                  >删除</el-button>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogCancle">取 消</el-button>
                <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
                <!-- <el-button type="primary" @click="">确 定</el-button> -->
              </div>
            </el-dialog>
            <!--弹出添加框end-->
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-input
              v-model="listQuery.shipmentNo"
              placeholder="发货单号"
              style="width: 90%;"
              class="filter-item"
              clearable
            />
          </el-col>
          <el-col :span="8">
            <el-upload
              v-loading="loading"
              :show-file-list="false"
              :http-request="excelUploadShipment"
              action="string"
              class="upload-demo"
              style="display: inline-block"
            >
              <el-button class="filter-item" type="primary" icon="el-icon-upload2">导入单据</el-button>
            </el-upload>
          </el-col>
        </el-row>

        <!--add by 2019-04-29 guoxiaoqing -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-select
              v-model="listQuery.proceedCompany"
              placeholder="收款公司"
              style="width: 90%;"
              filterable
              clearable
              @change="searchFrom"
            >
              <el-option
                v-for="proceedCompany in proceedCompanyList"
                :label="proceedCompany.text"
                :value="proceedCompany.value"
                :key="proceedCompany.value"
              />
            </el-select>
          </el-col>

          <el-col :span="8">
            <el-select
              v-model="listQuery.partnerName"
              placeholder="合作商"
              style="width: 90%;"
              filterable
              clearable
              @change="searchFrom"
            >
              <el-option
                v-for="partnerName in partnerList"
                :label="partnerName.text"
                :value="partnerName.value"
                :key="partnerName.value"
              />
            </el-select>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="18">
            <el-date-picker
              v-model="listQuery.time"
              :picker-options="pickerOptions"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
            />
          </el-col>
        </el-row>
      </div>

      <!-- 左侧table start  -->
      <el-table
        v-loading="listLoading"
        ref="singleTable"
        :data="talelist"
        :show-header="false"
        highlight-current-row
        height="400"
        @row-click="currentChangeTable"
      >
        <el-table-column prop="partnerName"/>
        <el-table-column prop="shipmentNo"/>
        <!-- <el-table-column prop="disName"/> -->
        <el-table-column prop="shipmentCreateDatetime">
          <template slot-scope="scope">
            <span>{{ scope.row.shipmentCreateDatetime | parseTime('{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 左侧table end  -->
      <el-row style="line-height:50px">
        <el-col :span="20">
          <el-lable>{{ statistics }}</el-lable>
        </el-col>
      </el-row>
      <!--分页-->
      <el-row type="flex" justify="space-around">
        <el-col :span="23">
          <div class="pagination-container">
            <el-pagination
              v-show="total>0"
              :current-page="listQuery.page"
              :page-sizes="[10,20,30, 50]"
              :page-size="listQuery.pageSize"
              :total="total"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-col>
      </el-row>
    </el-aside>

    <el-container>
      <el-header
        class="shipment_header"
        style="margin-left:15px;height: 700px; width:99%; border: 1px solid #eee;background-color:#fff;box-shadow: rgb(103, 96, 96) 2px 2px 5px"
      >
        <el-row :gutter="20">
          <el-col :span="10">
            <el-row :gutter="1">
              <el-col :span="5">
                <el-lable class="shipment_label" name="发货单号">发货单号:</el-lable>
              </el-col>
              <el-col :span="7">
                <div class="shipment_div">{{ shipmentObj.shipmentNo?shipmentObj.shipmentNo:"--" }}</div>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="10">
            <el-row :gutter="20">
              <el-col :span="10">
                <el-lable class="shipment_label" name="操作" style="clear: both;">操作:</el-lable>
              </el-col>
              <el-col :span="5">
                <el-button
                  :disabled="shipmentObj.recordStatus!=='N'"
                  type="danger"
                  size="mini"
                  @click="deleteShipmentByShipmentNo(shipmentObj)"
                >删除单据</el-button>
              </el-col>
              <!-- update 郭晓清 2019-03-27  发送后无法删除和修改-->
              <el-col :span="5">
                <el-button
                  :disabled="shipmentObj.recordStatus!=='N'"
                  type="warning"
                  size="mini"
                  @click="generateShipmentByNo(shipmentObj)"
                >发送</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-bottom: 15px;border: 1px dashed #eee"/>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-row :gutter="1">
              <el-col :span="6">
                <el-lable class="shipment_label" name="发货日期">发货日期:</el-lable>
              </el-col>
              <el-col :span="17">
                <div
                  class="shipment_div"
                >{{ shipmentObj.shipmentCreateDatetime| parseTime('{y}-{m}-{d}') }}</div>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row :gutter="1">
              <el-col :span="6">
                <el-lable class="shipment_label" name="合作商">合作商:</el-lable>
              </el-col>
              <el-col :span="17">
                <div
                  class="shipment_div"
                >{{ shipmentObj.supplierName?shipmentObj.supplierName:"--" }}</div>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="8">
            <el-row :gutter="1">
              <el-col :span="6">
                <el-lable class="shipment_label">收款公司:</el-lable>
              </el-col>
              <el-col :span="17">
                <div class="shipment_div">{{ (shipmentObj.proceedCompany) }}</div>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="8">
            <el-row :gutter="1">
              <el-col :span="6">
                <el-lable class="shipment_label" name="供应商">供应商:</el-lable>
              </el-col>
              <el-col :span="17">
                <div class="shipment_div">{{ (shipmentObj.partnerName) }}</div>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="8">
            <el-row :gutter="1">
              <el-col :span="6">
                <el-lable class="shipment_label" name="分销商">分销商:</el-lable>
              </el-col>
              <el-col :span="17">
                <div class="shipment_div">{{ shipmentObj.disName?shipmentObj.disName:"--" }}</div>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row :gutter="1">
              <el-col :span="6">
                <el-lable class="shipment_label" name="快递信息">快递信息:</el-lable>
              </el-col>
              <el-col :span="17">
                <div class="shipment_div">{{ shipmentObj.expressInfo?shipmentObj.expressInfo:"--" }}</div>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-row :gutter="1">
              <el-col :span="6">
                <el-lable class="shipment_label" name="入库单号">入库单号:</el-lable>
              </el-col>
              <el-col :span="17">
                <div class="shipment_div">{{ shipmentObj.instorageNo?shipmentObj.instorageNo:"--" }}</div>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row :gutter="1">
              <el-col :span="6">
                <el-lable class="shipment_label" name="出库单号">出库单号:</el-lable>
              </el-col>
              <el-col :span="17">
                <div
                  class="shipment_div"
                >{{ shipmentObj.outstorageNo?shipmentObj.outstorageNo:"--" }}</div>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row :gutter="1">
              <el-col :span="6">
                <el-lable class="shipment_label" name="上游总计">上游总计:</el-lable>
              </el-col>
              <el-col :span="17">
                <div class="shipment_div">￥{{ (shipmentObj.productUpTotalAmount) }}</div>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="8">
            <el-row :gutter="1">
              <el-col :span="6">
                <el-lable class="shipment_label" name="下游总计">下游总计:</el-lable>
              </el-col>
              <el-col :span="17">
                <div class="shipment_div">￥{{ shipmentObj.productDownTotalAmount }}</div>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="8">
            <el-row :gutter="1">
              <el-col :span="6">
                <el-lable class="shipment_label" name="发送状态">发送状态:</el-lable>
              </el-col>
              <el-col :span="17">
                <div class="shipment_div">{{ shipmentObj.recordStatus==='N'?'未发送':'已发送' }}</div>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-bottom: 15px;border: 1px dashed #eee"/>

        <el-row :gutter="20">
          <el-col :span="24">
            <!--物资明细表格 start-->
            <el-table
              :data="detailsList"
              border
              highlight-current-row
              header-align
              align="center"
              height="400"
            >
              <el-table-column property="productName" label="物品名称">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input
                      v-model="scope.row.productName"
                      min-width="50px"
                      class="edit-input"
                      size="small"
                    />
                  </template>
                  <span v-else>{{ scope.row.productName }}</span>
                </template>
              </el-table-column>
              <el-table-column property="productSpecifications" label="产品规格">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input
                      v-model="scope.row.productSpecifications"
                      min-width="50px"
                      class="edit-input"
                      size="small"
                    />
                  </template>
                  <span v-else>{{ scope.row.productSpecifications }}</span>
                </template>
              </el-table-column>

              <el-table-column property="productCnt" label="数量">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input
                      v-model="scope.row.productCnt"
                      min-width="10px"
                      class="edit-input"
                      size="small"
                    />
                  </template>
                  <span v-else>{{ scope.row.productCnt }}</span>
                </template>
              </el-table-column>

              <el-table-column property="productUpPrice" label="上游单价">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input
                      v-model="scope.row.productUpPrice"
                      min-width="10px"
                      class="edit-input"
                      size="small"
                    />
                  </template>
                  <span v-else>￥{{ scope.row.productUpPrice| currency }}</span>
                </template>
              </el-table-column>

              <el-table-column property="productDownPrice" label="下游单价">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input
                      v-model="scope.row.productDownPrice"
                      min-width="10px"
                      class="edit-input"
                      size="small"
                    />
                  </template>
                  <span v-else>￥{{ scope.row.productDownPrice | currency }}</span>
                </template>
              </el-table-column>

              <el-table-column property="productUpAmount" label="上游小计">
                <template slot-scope="scope">
                  <span>￥{{ scope.row.productUpAmount | currency }}</span>
                </template>
              </el-table-column>
              <el-table-column property="productDownAmount" label="下游小计">
                <template slot-scope="scope">
                  <span>￥{{ scope.row.productDownAmount | currency }}</span>
                </template>
              </el-table-column>

              <el-table-column property="productCategory" label="品类">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input
                      v-model="scope.row.productCategory"
                      min-width="10px"
                      class="edit-input"
                      size="small"
                    />
                  </template>
                  <span v-else>{{ scope.row.productCategory }}</span>
                </template>
              </el-table-column>
              <el-table-column property="productBrand" label="品牌">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input
                      v-model="scope.row.productBrand"
                      min-width="10px"
                      class="edit-input"
                      size="small"
                    />
                  </template>
                  <span v-else>{{ scope.row.productBrand }}</span>
                </template>
              </el-table-column>

              <el-table-column property="customerPhone" label="联系人电话">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input
                      v-model="scope.row.customerPhone"
                      min-width="10px"
                      class="edit-input"
                      size="small"
                    />
                  </template>
                  <span v-else>{{ scope.row.customerPhone }}</span>
                </template>
              </el-table-column>
              <el-table-column property="customerName" label="联系人名称">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input
                      v-model="scope.row.customerName"
                      min-width="10px"
                      class="edit-input"
                      size="small"
                    />
                  </template>
                  <span v-else>{{ scope.row.customerName }}</span>
                </template>
              </el-table-column>

              <el-table-column property="contactsName" label="客户名称">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input
                      v-model="scope.row.contactsName"
                      min-width="10px"
                      class="edit-input"
                      size="small"
                    />
                  </template>
                  <span v-else>{{ scope.row.contactsName }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="200">
                <template slot-scope="scope">
                  <el-button
                    v-if="!scope.row.edit && !scope.row.show"
                    type="danger"
                    size="small"
                    icon="el-icon-edit"
                    @click="deleteDetail(scope.row)"
                  >删除</el-button>
                  <el-button
                    v-if="scope.row.edit && !scope.row.show"
                    type="success"
                    size="small"
                    icon="el-icon-circle-check-outline"
                    @click="confirmEdit(scope.row)"
                  >修改</el-button>
                  <el-button
                    v-if="scope.row.edit && !scope.row.show"
                    class="cancel-btn"
                    size="small"
                    icon="el-icon-refresh"
                    type="warning"
                    @click="cancelEdit(scope.row)"
                  >取消</el-button>
                  <el-button
                    v-if="!scope.row.edit && !scope.row.show"
                    type="primary"
                    size="small"
                    icon="el-icon-edit"
                    @click="scope.row.edit=!scope.row.edit"
                  >编辑</el-button>
                  <el-alert v-if="scope.row.show" :closable="false" title="已发送无法修改" type="info"/>
                  <!-- <el-lable v-if="scope.row.show">已回收无法修改</el-lable> -->
                </template>
              </el-table-column>
            </el-table>
            <!--物资明细表格 end-->
          </el-col>
        </el-row>
      </el-header>
    </el-container>
  </el-container>
</template>

<script>
import {
  fetchList,
  getMaterialDetails,
  updateDetailByid,
  importMaterialDetails,
  deleteDetailByid,
  addShipmentAndDetails,
  deleteShipmentByShipmentNo,
  generateShipmentByNo,
  recoveryArchivesByshipmentNo,
  getPartnerInfo,
  importShipmentAndMaterialDetails
} from '@/api/shipment'
import { distributorList } from '@/api/payment'
import { parseTime } from '@/utils'
import { Mycurrency } from '@/utils/validate'
import { validateAmount } from '@/utils/validate'

export default {
  filters: {
    currency: Mycurrency
  },
  data() {
    var validateNumber = (rule, value, callback) => {
      if (!Number(value)) {
        callback(new Error('请输入数字值'))
      } else {
        const regu = /^[0-9]+(\.[0-9]{1,2})?$/
        const rsCheck = regu.test(value)
        if (!rsCheck) {
          callback(new Error('请输入正确的金额类型'))
        }
        callback()
      }
    }
    return {
      shipmentNo: null,
      disList: [],
      detailsList: [],
      partnerList: [
        {
          text: '美博',
          value: '美博'
        },
        {
          text: '星城',
          value: '星城'
        },
        {
          text: '北京盛世',
          value: '北京盛世'
        }
      ],
      proceedCompanyList: [
        {
          text: '深圳唯修汇科技有限公司',
          value: '深圳唯修汇科技有限公司'
        },
        {
          text: '浙江扳手科技有限公司',
          value: '浙江扳手科技有限公司'
        }
      ],
      supplierNameList: [],
      dialogFormVisible: false,
      talelist: null,
      shipmentObj: {},
      total: 1,
      listLoading: true,
      loading: false,
      listQuery: {
        page: 1,
        pageSize: 20,
        keyword: null,
        starTime: null,
        endTime: null,
        shipmentNo: null,
        proceedCompany: null,
        partnerName: null,
        time: null,
        pageNumber: null
      },
      rules: {
        proceedCompany: [
          { required: true, message: '请输入收款公司', trigger: 'blur' }
        ],
        supplierName: [
          { required: true, message: '请输入合作商', trigger: 'blur' }
        ],
        shipmentNo: [
          { required: true, message: '请输入发货单号', trigger: 'blur' }
        ],
        disId: [{ required: true, message: '请选择分销商', trigger: 'blur' }],
        partnerId: [
          { required: true, message: '请选择合作商', trigger: 'blur' }
        ],
        productTotalAmount: [{ validator: validateNumber, trigger: 'blur' }],
        createDatetime: [
          { required: true, message: '请选择发货时间', trigger: 'blur' }
        ],
        productPrice: [{ required: true, message: '123123', trigger: 'blur' }]
      },
      statistics: null,
      detailsJson: '',
      currentRow: null,
      dynamicValidateForm: {
        disId: null,
        disName: null,
        partnerId: null,
        partnerName: null,
        shipmentNo: null,
        supplierName: null,
        proceedCompany: null,
        productTotalAmount: null,
        createDatetime: null,
        archivesFlag: null,
        details: [
          {
            productName: '',
            productSpecifications: '',
            productCnt: '',
            productDownAmount: '',
            productUpAmount: '',
            productCategory: '',
            productBrand: '',
            productPrice: '',
            productUnit: ''
          }
        ]
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      time: ''
    }
  },
  created() {
    this.getList()
    this.getDistributorList()
    this.getPartnerInfo()
  },
  methods: {
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row)
      this.currentChangeTable(row)
    },
    currentChangeTable(row) {
      this.currentRow = row
      this.getMaterialDetails(row)
      if (this.talelist) {
        // 选择记录
        for (var i = 0; i < this.talelist.length; i++) {
          if (this.talelist[i].shipmentNo === row.shipmentNo) {
            this.shipmentObj = this.talelist[i]
          }
        }
      }
      console.log(this.shipmentObj)
    },
    formatterArchivesFlag(row, column) {
      if (row.archivesFlag && row.archivesFlag === 'Y') {
        return '已回收'
      } else {
        return '未回收'
      }
    },
    formatterRecordStatus(row, column) {
      if (row.recordStatus && row.recordStatus === 'N') {
        return '未生成'
      } else if (row.recordStatus && row.recordStatus === 'Y') {
        return '已生成'
      } else if (row.recordStatus && row.recordStatus === 'D') {
        return '已导出'
      } else if (row.recordStatus && row.recordStatus === 'U') {
        return '已修改'
      }
    },
    formatterUpRmb(row, column) {
      if (row.productUpAmount) {
        return '￥' + row.productUpAmount
      }
      if (row.productUpTotalAmount) {
        return '￥' + row.productUpTotalAmount
      }
    },
    formatterDownRmb(row, column) {
      if (row.productDownAmount) {
        return '￥' + row.productDownAmount
      }
      if (row.productDownTotalAmount) {
        return '￥' + row.productDownTotalAmount
      }
    },
    dialogCancle1(formName) {
      this.form = {}
      // this.$refs[formName].resetFields();
      this.dialogFormVisible = false
    },
    getMaterialDetails(row) {
      // 清空数据
      this.detailsList = null
      var flag = false
      if (row.recordStatus !== 'N') {
        flag = true
      }
      getMaterialDetails(row.shipmentNo)
        .then(response => {
          const items = response.data.data
          if (items) {
            this.detailsList = items.map(v => {
              this.$set(v, 'edit', false) // https://vuejs.org/v2/guide/reactivity.html
              this.$set(v, 'show', flag)
              return v
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getList() {
      this.listLoading = true
      this.listQuery.pageNumber =
        (this.listQuery.page - 1) * this.listQuery.pageSize
      fetchList(this.listQuery)
        .then(response => {
          if (response.data.status === 'success') {
            if (response.data.data.list.length === 0) {
              this.listLoading = false
              this.talelist = []
              this.shipmentObj = {}
              this.detailsList = []
              this.total = 1
              this.statistics = response.data.data.statistics
              return
            }
            this.total = response.data.data.total
            this.statistics = response.data.data.statistics
            this.talelist = response.data.data.list
            this.setCurrent(this.talelist[0])
            this.listLoading = false
          } else if (response.data.status === 'token_check_faild') {
            this.$message({
              message: response.data.messge,
              type: 'warning'
            })
            this.listLoading = false
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '数据加载失败',
            type: 'warning'
          })
          this.listLoading = false
        })
    },
    // 查询分销商
    getDistributorList() {
      distributorList().then(response => {
        this.disList = response.data.data
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    searchFrom() {
      if (this.listQuery.time !== null && this.listQuery.time !== '') {
        this.listQuery.starTime = parseTime(
          this.listQuery.time[0],
          '{y}-{m}-{d} {h}:{i}'
        )
        this.listQuery.endTime = parseTime(
          this.listQuery.time[1],
          '{y}-{m}-{d} {h}:{i}'
        )
      } else {
        this.listQuery.starTime = null
        this.listQuery.endTime = null
      }
      this.listQuery.pageNumber = 0
      this.listQuery.page = 1
      this.getList()
    },
    cancelEdit(row) {
      row.edit = false
      // this.getMaterialDetails(row)
      this.$message({
        message: '取消成功',
        type: 'warning'
      })
    },
    deleteShipmentByShipmentNo(val) {
      var data = {
        shipmentNo: val.shipmentNo
      }
      this.$confirm('此操作将永久删除该单据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteShipmentByShipmentNo(data)
            .then(response => {
              if (response.data.status === 'ok') {
                this.getList()
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: '删除失败',
                  type: 'warning'
                })
              }
            })
            .catch(error => {
              this.$message({
                message: '删除失败',
                type: 'warning'
              })
              console.log(error)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    recoveryArchivesByshipmentNo(val) {
      var data = {
        shipmentNo: val.shipmentNo
      }
      this.$confirm('回收单据后将无法修改, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          recoveryArchivesByshipmentNo(data)
            .then(response => {
              if (response.data.status === 'ok') {
                this.getList()
                this.$message({
                  message: '回收成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: '回收失败',
                  type: 'warning'
                })
              }
            })
            .catch(error => {
              this.$message({
                message: '回收失败',
                type: 'warning'
              })
              console.log(error)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消回收'
          })
        })
    },
    generateShipmentByNo(val) {
      if (val.recordStatus === 'Y') {
        this.$message({
          message: '该出入单据已经生成',
          type: 'success'
        })
        return
      } else if (val.archivesFlag === 'Y') {
        this.$message({
          message: '该单据已回收,不能生成',
          type: 'success'
        })
        return
      }
      var data = {
        shipmentNo: val.shipmentNo
      }
      this.$confirm('该操作后将无法修改上下游价格, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          generateShipmentByNo(data)
            .then(response => {
              if (response.data.status === 'ok') {
                this.getList()
                this.$message({
                  message: '生成成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: '生成失败',
                  type: 'warning'
                })
              }
            })
            .catch(error => {
              this.$message({
                message: '生成失败',
                type: 'warning'
              })
              console.log(error)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    deleteDetail(row) {
      var data = {
        materialDetailId: row.materialDetailId
      }
      this.$confirm('此操作将永久删除该物资明细, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteDetailByid(data)
            .then(response => {
              if (response.data.status === 'ok') {
                this.getList()
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: '删除失败',
                  type: 'warning'
                })
              }
            })
            .catch(error => {
              this.$message({
                message: '删除失败',
                type: 'warning'
              })
              console.log(error)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    confirmEdit(row) {
      if (!Number(row.productCnt)) {
        this.$message({
          message: '请输入数字值',
          type: 'warning'
        })
        return
      } else {
        if (row.productCnt > 5000000) {
          this.$message({
            message: '请输入小于5000000数字值',
            type: 'warning'
          })
          return
        }
      }
      if (!validateAmount(row.productUpPrice)) {
        this.$message({
          message: '输入正确的上游单价金额',
          type: 'warning'
        })
        return
      } else {
        if (row.productPrice > 5000000) {
          this.$message({
            message: '请输入小于5000000金额值',
            type: 'warning'
          })
          return
        }
      }

      if (!validateAmount(row.productDownPrice)) {
        this.$message({
          message: '输入正确的下游单价金额',
          type: 'warning'
        })
        return
      } else {
        if (row.productPrice > 5000000) {
          this.$message({
            message: '请输入小于5000000金额值',
            type: 'warning'
          })
          return
        }
      }

      row.edit = false
      var data = {
        materialDetailId: row.materialDetailId,
        productName: row.productName,
        productSpecifications: row.productSpecifications,
        productCnt: row.productCnt,
        productUpPrice: row.productUpPrice,
        productDownPrice: row.productDownPrice,
        shipmentNo: row.shipmentNo,
        productCategory: row.productCategory,
        productBrand: row.productBrand,
        customerName: row.customerName,
        customerPhone: row.customerPhone,
        contactsName: row.contactsName
      }
      updateDetailByid(data)
        .then(response => {
          if (response.data.status === 'ok') {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            // this.getMaterialDetails(row)
            this.getList()
          } else {
            this.$message({
              message: '修改失败',
              type: 'warning'
            })
          }
        })
        .catch(error => {
          this.$message({
            message: '修改失败',
            type: 'warning'
          })
          console.log(error)
        })
    },
    getShipmentNo(val) {
      this.shipmentNo = val
    },
    // 导入
    excelUpload(item) {
      var formData = new FormData()
      formData.append('importExcel', item.file)
      formData.append('shipmentNo', this.shipmentNo)
      importMaterialDetails(formData).then(response => {
        if (response.data.status === 'success') {
          this.getList()
          this.$message('导入成功')
        } else {
          this.$message('导入失败')
        }
      })
    },
    addDetail() {
      // 添加表单
      this.dynamicValidateForm.details.push({
        productName: '',
        productSpecifications: '',
        productCnt: '',
        productUpAmount: '',
        productDownAmount: '',
        productCategory: '',
        productBrand: '',
        productPrice: '',
        productUnit: ''
      })
    },
    // 导入发货单
    excelUploadShipment(item) {
      // console.log(item.file)
      this.loading = true
      var formData = new FormData()
      formData.append('importExcel', item.file)
      importShipmentAndMaterialDetails(formData)
        .then(response => {
          if (response.data.status === 'success') {
            this.$message({
              message: '导入成功！',
              type: 'success'
            })
            this.loading = false
            setTimeout(() => {
              this.getList()
            }, 1.5 * 1000)
          } else {
            this.$message(response.data.messge)
            this.loading = false
            setTimeout(() => {
              this.getList()
            }, 10 * 1000)
          }
        })
        .catch(error => {
          console.log('===================' + error)
        })
    },
    removeDetail(item) {
      // 删除表单
      var index = this.dynamicValidateForm.details.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.details.splice(index, 1)
      }
    },
    submitForm(formName) {
      // 提交集合表单
      this.$refs[formName].validate(valid => {
        if (valid) {
          var time = parseTime(
            this.dynamicValidateForm.shipmentCreateDatetime,
            '{y}-{m}-{d}'
          )
          this.dynamicValidateForm.shipmentCreateDatetime = time

          var disName
          for (var i = 0; i < this.disList.length; i++) {
            if (this.disList[i].disId === this.dynamicValidateForm.disId) {
              disName = this.disList[i].disName
            }
          }
          this.dynamicValidateForm.disName = disName

          var partnerName
          for (var j = 0; j < this.supplierNameList.length; j++) {
            if (
              this.supplierNameList[j].value ===
              this.dynamicValidateForm.partnerId
            ) {
              partnerName = this.supplierNameList[j].text
            }
          }
          this.dynamicValidateForm.partnerName = partnerName
          console.log(
            '===========' +
              JSON.stringify(this.$refs['dynamicValidateForm'].model)
          )
          this.detailsJson = JSON.stringify(
            this.$refs['dynamicValidateForm'].model
          )
          var param = {
            detailsJson: this.detailsJson
          }
          addShipmentAndDetails(param)
            .then(response => {
              if (response.data.status === 'success') {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                setTimeout(() => {
                  this.dialogFormVisible = false
                  this.dialogCancle()
                  this.getList()
                }, 1.5 * 1000)
              } else {
                this.$message({
                  message: '添加失败：' + response.data.messge,
                  type: 'error'
                })
                this.dialogCancle()
              }
            })
            .catch(error => {
              console.log(error)
              this.dialogCancle()
              this.listLoading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(item) {
      // 清空表单
      var index = this.dynamicValidateForm.details.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.details.splice(index, 1, {
          productName: '',
          productSpecifications: '',
          productCnt: '',
          productUpAmount: '',
          productDownAmount: '',
          productCategory: '',
          productBrand: '',
          productPrice: '',
          customerPhone: '',
          customerName: '',
          productUnit: ''
        })
      }
    },
    getPartnerInfo(item) {
      // 查询合作商信息
      getPartnerInfo()
        .then(response => {
          if (response.data.status === 'ok') {
            this.supplierNameList = response.data.data
          } else {
            console.log('合作商加载失败！')
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    dialogCancle() {
      this.dialogFormVisible = false
      this.dynamicValidateForm = {
        disId: null,
        partnerName: null,
        shipmentNo: null,
        proceedCompany: null,
        supplierName: null,
        productTotalAmount: null,
        createDatetime: null,
        details: [
          {
            productName: '',
            productSpecifications: '',
            productCnt: '',
            productDownAmount: '',
            productUpAmount: '',
            productCategory: '',
            productBrand: '',
            productPrice: '',
            productUnit: ''
          }
        ]
      }
    }
  }
}
</script>

<style>
.shipment_label {
  float: left;
  font-family: 'Microsoft Yahei';
  font-size: 14px;
  font-weight: 700;
}

.shipment_div {
  float: left;
  font-family: 'Microsoft Yahei';
  font-size: 13px;
  font-weight: 500;
}
.material-filter-container > .el-row,
.shipment_header {
  border: 1px;
  color: #333;
  line-height: 50px;
}

.el-aside {
  color: #333;
  line-height: 400px;
}

.el-main {
  color: #333;
  text-align: center;
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.el-container:nth-child(5) .el-aside {
  line-height: 260px;
}
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}
.el-pagination__total,
.el-pagination__sizes,
.btn-prev,
.el-pager,
.btn-next,
.el-pagination__jump {
  margin-top: 2px !important;
}
.el-pagination {
  line-height: 1px;
  white-space: pre-wrap;
}
.el-table__body tr.current-row > td {
  background-color: #dde9fc;
}
</style>
